﻿using FastExecutor.Base.Design;
using FastExecutor.Base.Util;
using FastExecutor.Message.Application;
using FastExecutor.ORG.Entity;
using FastExecutor.ORG.Enum;
using FastIOC.Annotation;
using FastUtil;
using FastUtil.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastExecutor.ORG.DB
{
    public class DB_User : FastTemplateDB<Frame_User>
    {
        [AutoWired]
        private DB_Config @DB_Config;
        public override void Insert(Frame_User Entity)
        {
            if (null == Entity.RowGuid || string.IsNullOrEmpty(Entity.RowGuid))
            {
                Entity.RowGuid = CommonUtil.CreateCommonGuid();
            }
            Entity.AddDate = DateTime.Now;
            Entity.PassWord = EncryptUtil.MD5Encrypt(Entity.LoginID + "|" + @DB_Config.GetConfigValue("DefaultPWD"));
            base.Insert(Entity);
        }

        public override void Delete(string KeyGuid)
        {
            string sql = string.Format("delete from frame_userrolerelation where UserGuid='{0}'", KeyGuid);
            @DBUtil.ExecuteSQL(sql);
            base.Delete(KeyGuid);
        }

        public override void BatchDelete(List<string> KeyGuidList)
        {
            foreach (string KeyGuid in KeyGuidList)
            {
                @DBUtil.ExecuteSQL(string.Format("delete from frame_userrolerelation where UserGuid='{0}'", KeyGuid));
                @DBUtil.ExecuteSQL(string.Format("delete from Frame_ModuleRight where RightGuid='{0}'", KeyGuid));
            }
            base.BatchDelete(KeyGuidList);
        }


        public void InitPWD(string UGuid)
        {
            Frame_User Entity = FindOne(UGuid);
            string DefaultPWD = @DB_Config.GetConfigValue("DefaultPWD");
            Entity.PassWord = EncryptUtil.MD5Encrypt(Entity.LoginID + "|" + DefaultPWD);
            Update(Entity);
            string OperateContent = string.Format("重置密码，用户名：{0},密码:{1}",Entity.DisplayName,DefaultPWD);
            Frame_OperateLog LogEntity = new Frame_OperateLog("Frame", OperateContent);
            MessageCenter.GetInstance().SendMessage(FrameEnum.LogType.Operate.ToString(), LogEntity);
        }

        public void ChangeEnable(string UGuid, int IsEnable)
        {
            Frame_User Entity = FindOne(UGuid);
            Entity.IsEnable = IsEnable;
            Update(Entity);
        }

        public Frame_User FindOne_LoginID(string LoginID)
        {
            string sql = string.Format("select * from Frame_User where LoginID='{0}'",LoginID);
            List<Frame_User> List = DBUtil.FindList<Frame_User>(sql);
            if (List.Count>0)
            {
                return List[0];
            }
            else
            {
                return null;
            }
        }
    }
}
